
import ajax from '../../../until/request.js'

import { goRmd, searchValue, render, top, lazyImg } from '../../public/js/public.js'


class Index {
  constructor() {
    this.init()
  }
  init () {
    this.getDoms()
    this.logout()
    this.toRmd()
    this.getRenderData()
    this.changeInfo()
    this.searchValue()
    this.updatePassword()
    top()
    window.onload = () => { lazyImg() }
    window.addEventListener("scroll", lazyImg)
    this.checkTokenExpiration()
  }
  getDoms () {
    this.info = document.querySelector(".perInfo")
    // 获取退出按钮
    this.quitLogin = document.querySelector(".quitLogin")
    // 获取设置按钮
    this.setting = document.querySelector(".setting")
    //获取 修改信息按钮
    this.setInfo = document.querySelector(".setInfo")
    // 获取修改密码按钮
    this.revisePwd = document.querySelector("#revisePwd")
    // 获取  userInfo
    this.userInfo = JSON.parse(localStorage.getItem("userInfo")) || ""
    // 获取用户id
    this.user_id = JSON.parse(localStorage.getItem("user_id"))
    // 获取个人主页
    this.homePage = document.querySelector(".homePage")
    // 获取购物车
    this.goCar = document.querySelector(".goCar")
    // 获取搜索框
    this.search = document.querySelector("#search")
    this.searchBtn = document.querySelector("#searchBtn")
  }
  // 检查token 是否过期
  checkTokenExpiration () {
    if (this.userInfo.token) {
      let currentTimestamp = new Date().getTime() // 当前时间戳
      let expirationTimestamp = currentTimestamp + 3600000 // 过期时间戳（当前时间戳 + 1小时）

      if (currentTimestamp > expirationTimestamp) {
        // token 过期
        localStorage.removeItem("user_id")
      }

    }
  }

  //退出登录
  logout () {
    //  判断  localStorage 是否有数据 

    if (this.user_id != undefined) {
      this.info.querySelector("a").style.display = "none"
      this.info.innerHTML = ` <span class="iconfont icon-geren"></span><span >${this.userInfo.username}<span/>`
      this.quitLogin.style.display = "block"
      this.homePage.style.display = "block"
    } else {
      this.info.querySelector("a").style.display = "block"
      this.quitLogin.style.display = "none"
      this.homePage.style.display = "none"
    }
    // 退出登录  删除localStorage中的数据
    this.quitLogin.addEventListener("click", () => {
      this.info.innerHTML = ""
      localStorage.removeItem("user_id")
    })
    // 点击设置按钮判断是否登录
    this.setting.addEventListener("click", () => { this.isLogin() })
    // 点击购物车判断
    this.goCar.addEventListener("click", (e) => {
      this.isLogin() ? "" : e.preventDefault()
    })
    // 点击个人主页判断
    this.homePage.addEventListener("click", (e) => {
      this.isLogin() ? "" : e.preventDefault()
    })
  }

  //  渲染 个人信息页面
  renderPersonInfo (infoData) {
    //  获取 对应的元素
    this.infoID = document.querySelector("#infoID")
    this.infoNickname = document.querySelector("#infoNickname")
    this.infoUsername = document.querySelector("#infoUsername")
    this.infoIdentity = document.querySelector("#infoIdentity")
    this.infoGender = document.querySelector("#infoGender")
    this.infoAge = document.querySelector("#infoAge")
    this.infoPhoneNum = document.querySelector("#infoPhoneNum")
    //  渲染数据
    // console.log(infoData.info)
    infoID.value = infoData.info.id
    infoNickname.value = infoData.info.nickname
    infoUsername.value = infoData.info.username
    infoIdentity.value = infoData.info.identity
    infoGender.value = infoData.info.gender
    infoAge.value = infoData.info.age
    infoPhoneNum.value = infoData.info.phonenum
  }
  isLogin () {
    if (this.user_id == undefined) {
      alert("请先登录")
      const dropdownMenu = document.querySelector(".dropdown-menu")
      dropdownMenu.style.display = "none"
      return false
    }
    return true
  }
  //更改个人信息
  changeInfo () {
    // 关闭按钮
    document.querySelectorAll(".btnOff").forEach(item => {
      item.addEventListener("click", function () {
        const parentElement = item.closest(".activeBlock")
        if (parentElement) {
          parentElement.classList.remove("activeBlock")
        }
      })
    })

    //  修改个人信息  事件委托
    this.setInfo.addEventListener("click", (e) => {
      // console.log(1)
      let setData = Array.from(document.querySelectorAll(".setData"))
      //  判断 点击 更改个人信息
      if (e.target.id == "changePersonInfo") {
        // document.querySelector(".changeInfo").style.display = "block"
        setData.map((item) => item.classList.remove("activeBlock"))
        document.querySelector(".changeInfo").classList.add("activeBlock")
        //  拿到id  和 token 


        //  获取拿到的个人信息
        let updateInfo = ajax.getPro({
          url: "http://localhost:8888/users/info",
          params: { "id": this.userInfo.user_id },
          token: this.userInfo.token
        })
        updateInfo.then((res) => {
          // 渲染个人信息
          let infoData = JSON.parse(res)
          console.log(infoData)
          this.renderPersonInfo(infoData)

        })
      }
      if (e.target.id == "changePersonPwd") {
        setData.map((item) => item.classList.remove("activeBlock"))
        document.querySelector(".changePwd").classList.add("activeBlock")

      }

    })
    // 修改个人信息
    document.querySelector("#reviseInfo").addEventListener("click", (e) => {
      e.preventDefault()

      // 发送ajax请求  更新数据 
      let reviseInfo = ajax.postProToken({
        url: "http://localhost:8888/users/update",
        params: {
          "id": this.infoID.value,
          "nickname": this.infoNickname.value,
          "username": this.infoUsername.value,
          "identity": this.infoIdentity.value,
          "phonenum": this.infoPhoneNum.value,
          "gender": this.infoGender.value,
          "age": this.infoAge.value
        },
        token: this.userInfo.token
      })
      // 相应ajax请求 
      reviseInfo.then((res) => {
        let message = JSON.parse(res)
        // 判断 响应码  是否 成功
        if (message.code == 1) {
          // 成功  提示 成功信息
          let reviseSuccessAlert = document.querySelector(".reviseSuccessAlert")
          reviseSuccessAlert.style.display = "block"
          setTimeout(() => {
            reviseSuccessAlert.style.display = "none"

          }, 1000)
        }
        // 不成功   提示 错误信息
        if (message.code != 1) {
          // console.log(message.message)
          let reviseFailAlert = document.querySelector(".reviseFailAlert")
          reviseFailAlert.style.display = "block"
          reviseFailAlert.innerHTML = `${message.message}`
          setTimeout(() => {
            reviseFailAlert.style.display = "none"
          }, 2000)
        }

      })

    })


  }
  // 修改密码
  updatePassword () {
    this.revisePwd.addEventListener("click", () => {
      //  获取 输入框的值
      const oldPassword = document.querySelector("#oldPwd").value
      const newPassword = document.querySelector("#newPwd").value
      const rNewPassword = document.querySelector("#confirmPwd").value
      //  发送 请求
      const revisePwd = ajax.postProToken({
        url: "http://localhost:8888/users/rpwd",
        params: {
          id: this.userInfo.user_id,
          oldPassword,
          newPassword,
          rNewPassword
        },
        token: this.userInfo.token
      })
      revisePwd.then(res => {
        let message = JSON.parse(res)
        console.log(message)
        if (message.code == 1) {
          // 成功  提示 成功信息
          let revisePwdSuccessAlert = document.querySelector(".revisePwdSuccessAlert")
          revisePwdSuccessAlert.style.display = "block"
          setTimeout(() => {
            revisePwdSuccessAlert.style.display = "none"
            location.href = "../login/login.html"
            localStorage.clear()
          }, 1000)

        }
        // 不成功   提示 错误信息
        if (message.code == 0) {
          // console.log(message.message)
          // console.log(document.querySelector(".revisePwdFailAlert"))
          let revisePwdFailAlert = document.querySelector(".revisePwdFailAlert")
          revisePwdFailAlert.style.display = "block"
          revisePwdFailAlert.innerHTML = `${message.message}`
          setTimeout(() => {
            revisePwdFailAlert.style.display = "none"
          }, 2000)
        }
      })
    })
  }
  // 请求数据
  getRenderData () {
    // 请求数据 
    ajax.getPro({
      url: 'http://localhost:8888/goods/list',
      params: {
        pagesize: 1000, // 每页多少条数据
      }
    }).then(res => {
      render(JSON.parse(res).list, ["热门推荐"], "popularRecommendations")
      render(JSON.parse(res).list, ["男装", "男鞋"], "manWear")
      render(JSON.parse(res).list, ["女装", "首饰"], "montblancStar")
      render(JSON.parse(res).list, ["智能", "手机"], "intellect")
      render(JSON.parse(res).list, ["海外购"], "overseasPurchase")
      render(JSON.parse(res).list, ["童装", "母婴"], "infantAndmom")
    })

  }
  // 点击 跳转 详情页
  toRmd () {
    document.querySelector('.home-main ').addEventListener("click", e => {
      this.isLogin() ? "" : e.preventDefault()
      const boxItem = e.target.closest('.box-item')
      if (boxItem) {
        // console.log(boxItem.dataset.id)
        this.userInfo.good_id = boxItem.dataset.id
        localStorage.setItem("userInfo", JSON.stringify(this.userInfo))
      }
    })
  }

  //搜索功能
  searchValue () {
    this.searchValue = searchValue
    this.searchValue()
  }

}
let index = new Index()


export default index